<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Exception\AccessDenyException;
use App\Service\Admin\AdminService;
use App\Utils\ContextUtil;
use App\Utils\JWT\Exceptions\TokenInvalidException;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AdminAuthMiddleware implements MiddlewareInterface
{

    // 需要登录但是不需要权限
    protected $exceptRoutes = [
        '/auth/admin/login/out',
        '/admin/rbac/manager/updateSelfLoginPwd',
        '/admin/rbac/manager/currManagerInfo',
    ];

    public function __construct(protected ContainerInterface $container, RequestInterface $request)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 当前登录的管理员
        $adminInfo = ContextUtil::getAdmin();
        if (!$adminInfo){
            throw new TokenInvalidException('请先登录');
        }
        if (in_array($request->getUri()->getPath(),$this->exceptRoutes)){
            return $handler->handle($request);
        }
        $pathInfo = ContextUtil::getPathInfo();
        $hasAcc = \Hyperf\Support\make(AdminService::class)->adminHasAccessRoute($adminInfo, $pathInfo['id']);
        if (!$hasAcc){
            throw new AccessDenyException();
        }
        return $handler->handle($request);
    }
}
